import java.util.ArrayDeque;
import java.util.Deque;

public class Calculate2 {
    // 基本计算器II
    // https://leetcode.cn/problems/basic-calculator-ii/description/
    public int calculate(String s) {
        Deque<Integer> nums = new ArrayDeque<>();
        // 通过op来记录将要进行的计算的运算符
        char op = '+';
        char[] ch = s.toCharArray();
        int index = 0;
        while (index < ch.length) {
            if (ch[index] == ' ') {
                index++;
            } else if (ch[index] == '+' || ch[index] == '-'
                    || ch[index] == '*' || ch[index] == '/') {
                op = ch[index++];
            } else {
                int num = 0;
                while (index < ch.length && Character.isDigit(ch[index])) {
                    num = num * 10 + (ch[index++] - '0');
                }
                if (op == '-') {
                    num = -num;
                } else if (op == '*') {
                    num = nums.poll() * num;
                } else if (op == '/') {
                    num = nums.poll() / num;
                }
                nums.push(num);
            }
        }
        while (nums.size() > 1) {
            int num1 = nums.poll();
            int num2 = nums.poll();
            nums.push(num1 + num2);
        }
        return nums.poll();
    }

    public static void main(String[] args) {
        System.out.println(new Calculate2().calculate(" 3+5 / 2 "));
    }
}
